package com.xunqi.ad.service.impl;

import com.xunqi.ad.entity.AdUser;
import com.xunqi.ad.enums.ResponseEnum;
import com.xunqi.ad.exception.AdException;
import com.xunqi.ad.form.CreateUserForm;
import com.xunqi.ad.repository.AdUserRepository;
import com.xunqi.ad.service.IUserService;
import com.xunqi.ad.utils.CommonUtils;
import com.xunqi.ad.vo.CreateUserResponseVo;
import com.xunqi.ad.vo.ResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @Description:
 * @Created with IntelliJ IDEA.
 * @author: 夏沫止水
 * @create: 2020-04-29 15:46
 **/
@Slf4j
@Service("userService")
public class UserServiceImpl implements IUserService {

    @Resource
    private AdUserRepository adUserRepository;


    /**
     * 创建用户
     * @param form
     * @return
     * @throws AdException
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseVo<CreateUserResponseVo> createUser(CreateUserForm form) throws AdException {

        //查询一下数据库是否有用户名相同的用户
        AdUser oldUser = adUserRepository.findByUsername(form.getUsername());

        //若用户名已存在则提示用户已存在
        if (oldUser != null) {
            return ResponseVo.error(ResponseEnum.USERNAME_EXIST);
        }

        //执行创建用户的方法
        AdUser newUser = new AdUser(form.getUsername(), CommonUtils.md5(form.getUsername()));

        AdUser userSave = adUserRepository.save(newUser);

        CreateUserResponseVo createUserResponseVo = new CreateUserResponseVo();
        BeanUtils.copyProperties(userSave,createUserResponseVo);

        return ResponseVo.success(createUserResponseVo);
    }
}
